package com.ahwei.util;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author：ahwei163@qq.com
 *
 * @date: 202*-03-22 11:37:02
 * @description: 文件工具类！
 */
public class FileUtils {
    //创建上传文件的保存路径
    String uploadDir = this.getClass().getResource("/").getPath().replace("/WEB-INF/classes/", "/upload/");

    /**
     * 文件上传
     *
     * @param request ·
     * @return ·
     */
    public static Map<String, String> fileUpload(HttpServletRequest request){
        Map<String, String> kvMap = new HashMap<>();
        //获得磁盘文件工厂
        DiskFileItemFactory factory = new DiskFileItemFactory();
        File file = new File("D:\\YOHO\\");
        if (!file.exists()) file.mkdirs();
        //设置工厂的临时文件目录：当上传文件的大小大于缓冲区大小时，将使用临时文件目录缓存上传的文件
        factory.setRepository(file);
        //文件上传解析器
        ServletFileUpload upload = new ServletFileUpload(factory);
        //设置所有上传数据的最大值，单位字节long  1M
        upload.setSizeMax(1024 * 1024 * 1024);
        //设置单个文件上传的最大值
        upload.setFileSizeMax(1024 * 1024 * 1024);
        //设置编码格式
        upload.setHeaderEncoding("UTF-8");
        try {
            //解析请求，将表单中每个输入项封装成一个FileItem对象
            List<FileItem> itemList = upload.parseRequest(request);
            for (FileItem item : itemList) {
                //判断输入的类型是 普通输入项 还是文件
                if (item.isFormField()) {
                    //普通输入项 ,得到input中的name属性的值
                    String name = item.getFieldName();
                    //得到输入项中的值
                    String value = item.getString("UTF-8");
                    kvMap.put(name, value);
                } else {
                    try {
                        //返回表单标签name属性的值
                        String name = item.getFieldName();
                        //上传的是文件，获得文件上传字段中的文件名
                        //注意IE或FireFox中获取的文件名是不一样的，IE中是绝对路径，FireFox中只是文件名。
                        String fileName = item.getName();
                   /* //获取后缀
                    String exName = fileName.substring(fileName.lastIndexOf("."));
                    fileName = UUID.randomUUID().toString().replace("-","")+exName;
                    */
                        //保存文件名
                        kvMap.put(name, fileName);

                        //方法一：保存上传文件到指定的文件路径
                        InputStream in = item.getInputStream();
                        //创建上传文件的保存路径
                        String uploadDir = FileUtils.class.getResource("/").getPath().replace("/WEB-INF/classes/", "/upload/");
                        File files = new File(uploadDir);
                        if (!files.exists()) files.mkdirs();
                        FileOutputStream out = new FileOutputStream(uploadDir + fileName);
                        byte[] buff = new byte[1024];
                        while (in.read(buff) > 0) {
                            out.write(buff);
                        }
                        in.close();
                        out.close();
                    } catch (IOException e) {
                        throw new RuntimeException("文件上传失败，请检查");
                    }
                }
            }
            File[] files = file.listFiles();
            //遍历该目录下的文件对象
            for (File f: files != null ? files : new File[0]){
                f.delete();
            }

        } catch (Exception e) {
            throw new RuntimeException(e.getMessage());
        }
        return kvMap;
    }

    /**
     * 文件下载
     * @param request ·
     * @param response ·
     * @throws UnsupportedEncodingException ·
     */
    public static void fileDownload(HttpServletRequest request, HttpServletResponse response, String fileName) throws UnsupportedEncodingException {
        //获取文件的路径
        String dataDirectory = request.getServletContext().getRealPath("/upload/");
        request.setCharacterEncoding("UTF-8");

        LogUtils.info(dataDirectory+fileName);
        //创建文件对象
        File file = new File(dataDirectory, fileName);
        //文件存在则执行下载动作
        if (file.exists()) {
            //设置要下载文件类型  参考：https://www.w3school.com.cn/media/media_mimeref.asp
            response.setContentType("video/mpeg4");
            //向响应头中，设置添加Content-Disposition键值对，告诉浏览器做文件下载
            response.addHeader("Content-Disposition","attachment; filename=" + fileName + "");
            //设置文件长度
            response.addHeader("Content-Length", String.valueOf(file.length()));

            byte[] buffer = new byte[1024];

            try (FileInputStream fis = new FileInputStream(file); BufferedInputStream bis = new BufferedInputStream(fis)) {
                OutputStream os = response.getOutputStream();
                int len = bis.read(buffer);
                while (len != -1) {
                    os.write(buffer, 0, len);
                    len = bis.read(buffer);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        } else {
            LogUtils.info("文件不存在!");
        }
    }

    /**
     * 判断文件是否存在
     * @param filePath ·
     * @return ·
     */
    public static boolean exists(String filePath){
        //创建文件对象
        File file = new File(filePath);
        return file.exists();
    }
}
